<template>
  <div class="page">
    <global-header title="反馈详情" @back="$router.back()" />
    <main class="page-main">
      <div class="history-detail-container">
        <div class="feedback-title">
          {{ detailTitle }}
        </div>

        <div
          class="history-reply-container"
          ref="vanListRef"
          :style="{
            height: form.imgs.length > 3 ? 'calc(100vh - 440px)' : 'calc(100vh - 370px)'
          }"
        >
          <div class="reply-item" v-for="(item, index) in replyList" :key="index">
            <div class="reply-item-wrap">
              <div class="reply-item-top">
                <div class="reply-item-left">
                  <img class="avatar" :src="netPath(roomInfo?.SysImg)" />
                  <div class="reply-info-my">
                    我的反馈<span>({{ item.AdminName }})</span>
                  </div>
                </div>
                <div class="reply-item-right">{{ formatDate(item.CreatedAt) }}</div>
              </div>
              <div class="reply-info">
                <div class="feedback-content">
                  <div class="text-content">{{ item.Content }}</div>
                  <div v-if="item.Imgs" class="image-gallery">
                    <img
                      v-for="img in item.Imgs.split(',')"
                      :key="img"
                      :src="netPath(img)"
                      class="image-item"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="apply" :class="{ mh: form.imgs.length > 3 }">
          <textarea
            id="content"
            class="form-textarea"
            v-model="form.content"
            placeholder="请输入你的反馈内容"
          ></textarea>
          <div class="upload">
            <van-uploader
              v-model="form.images"
              :deletable="true"
              :preview-size="71"
              :after-read="onAfterRead"
              :max-count="5"
            >
            </van-uploader>
          </div>
        </div>
        <van-button class="btn" block type="primary" @click="onApply" :disabled="state.loading"
          >确认提交</van-button
        >
      </div>
    </main>
  </div>
</template>
<route>
  {
    name: "admin-main-feedback-detail",
    meta: {
      pageIndex: 5,
    }
  }
</route>
<script setup lang="ts">
import { reqFeedbackReplyList, reqFeedbackReply } from "@/api/main";
import { showSuccessToast } from "vant";
import { formatDate, netPath } from "@/utils/common";
import { useRoomStore } from "@/store/modules/room";
import { storeToRefs } from "pinia";
import { toast } from "@/utils/toast";
import { reqUploadImg } from "@/api/user";
import { debounce } from "lodash-es";
import { useRoute } from "vue-router";
const router = useRoute();
const roomStore = useRoomStore();
const { roomInfo } = storeToRefs(roomStore);

const detailTitle = ref<any>(null);
const state = reactive({
  subLoading: false,
  replyLoading: false,
  loading: false,
  finished: false
});
const replyList = ref<any[]>([]);
const form = ref({
  content: "",
  images: [] as any[],
  imgs: [] as any[]
});
const vanListRef = ref();

const scrollToBottom = () => {
  if (vanListRef.value) {
    const h = vanListRef.value?.scrollHeight;
    vanListRef.value?.scrollTo({ top: h, behavior: "smooth" });
  }
};

const getDataReply = async () => {
  const { id, title } = router.query;
  if (!id) return;
  detailTitle.value = title;
  try {
    state.subLoading = true;
    const res = await reqFeedbackReplyList({
      Id: id
    });
    res.data.sort((a, b) => new Date(a.CreatedAt).getTime() - new Date(b.CreatedAt).getTime());
    replyList.value = res.data;
    state.subLoading = false;
    nextTick(() => {
      scrollToBottom();
    });
  } catch (error) {
    state.subLoading = false;
    console.log(error);
  }
};

const onAfterRead: any = async (file: any) => {
  const isIMAGE = file.file.type === "image/jpeg" || "image/jpg" || "image/png";
  const isLt200K = file.file.size / 1024 < 200;

  if (!isIMAGE) {
    return toast.fail("上传文件只能是图片格式!");
  }
  if (!isLt200K) {
    return toast.fail("发送图片大小不能超过 200KB!");
  }
  const loading = toast.loading("上传中...");
  try {
    let param = new FormData();
    param.append("ImgPath", file.file);
    const res = await reqUploadImg(param);
    form.value.imgs = [...form.value.imgs, res.data.ImgPath];
    file.status = "done";
    loading.close();
  } catch (error) {
    loading.close();
    file.status = "failed";
    console.log(error);
  }
};

const onApply = debounce(
  async () => {
    if (!form.value.content.trim()) {
      return showToast("反馈内容不能为空");
    }
    const payload = {
      Content: form.value.content,
      Id: Number(router.query?.id),
      Imgs: form.value.imgs.length > 0 ? form.value.imgs.join(",") : null
    };
    try {
      state.loading = true;
      await reqFeedbackReply(payload);
      state.loading = false;
      form.value.content = "";
      form.value.imgs = [];
      form.value.images = [];
      showSuccessToast("回复成功");
      getDataReply();
    } catch (err) {
      state.loading = false;
    }
  },
  500,
  { leading: true, trailing: false }
);

onMounted(() => {
  getDataReply();
});
</script>

<style scoped lang="scss">
.page-main {
  padding: 10px;
  background-color: #ffffff;
  position: relative;
  overflow: hidden;
}

.history-detail-container {
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.feedback-title {
  padding: 17px 0;
  font-size: 16px;
  border-bottom: 1px solid #e4e4e4;
  font-family: PingFang SC, PingFang SC;
}

.history-reply-container {
  border-radius: 8px;
  margin-top: 10px;
  overflow-y: auto;
}

.reply-item {
  margin-bottom: 25px;

  &-wrap {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }

  &-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  &-left {
    display: flex;
    gap: 10px;
    align-items: center;
  }
}

.avatar {
  width: 24px;
  height: 24px;
  border-radius: 10px;
}

.reply-info {
  flex-grow: 1;

  &-my {
    line-height: 24px;

    span {
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      font-size: 12px;
      color: rgba(0, 7, 33, 0.3);
    }
  }
}

.feedback-content {
  background-color: #ebf6f9;
  padding: 12px;
  border-radius: 8px;
}

.text-content {
  font-family: PingFang SC, PingFang SC;
  font-weight: 500;
  font-size: 13px;
  color: #111111;
}

.image-gallery {
  display: flex;
  flex-wrap: wrap;
  margin-top: 24px;
}

.image-item {
  width: 71px;
  height: 71px;
  margin-right: 10px;
  border-radius: 5px;
  object-fit: cover;
}

.timestamp {
  color: #999;
  font-size: 12px;
  margin-top: 10px;
}
.apply {
  position: relative;
  width: calc(100% - 20px);
  background: #f6f9fe;
  padding: 10px;
  border-radius: 5px;
  height: 160px;
  &.mh {
    height: 230px;
  }
}

.form-textarea {
  width: 100%;
  font-size: 14px;
  border: none;
  background: #f6f9fe;
  color: rgba(17, 17, 17, 0.8);

  &::placeholder {
    color: rgba(17, 17, 17, 0.3);
  }
}
.form-textarea {
  height: 60px;
}

.upload {
  position: absolute;
  bottom: 10px;
  left: 10px;

  :deep(.van-uploader__wrapper) {
    border-radius: 8px;

    .van-uploader__upload {
      margin: 0;
      background-color: #ffffff;
      border-radius: 8px;
    }

    .van-image {
      border-radius: 8px;
    }
  }
}
.btn {
  margin-top: 10px;
}
</style>
